﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UI_RoomList : BaseUI {

    List<UI_RoomItem> roomItem_list = new List<UI_RoomItem>();
    public override UIConst UI_Type
    {
        get
        {
            return UIConst.UI_RoomList;
        }
    }

    public GameObject roomItemPrefab;
    public Transform ItemContain;
    public Button createRoomBtn,leaveBtn;

    private void Awake()
    {
        

        createRoomBtn.onClick.AddListener(OnCreateRoomBtn);
        leaveBtn.onClick.AddListener(OnLeaveBtn);
        //SpwanRoomItem(new RoomData());
    }

    private void OnLeaveBtn()
    {
        UIManager.Instantce.Close(this.UI_Type,this.ui_Id);
        UIManager.Instantce.Open(UIConst.UI_StartMenu);
        //RoomMgr.Instantce.QuitRoom();
    }

    private void OnCreateRoomBtn()
    {
        UIManager.Instantce.Open(UIConst.UI_CreateRoom);
    }
    private void OnEnable()
    {
        RoomMgr.Instantce.StartCheckRoom();
        EventCentre.Instantce.AddEventListener(EventDefine.OnRoomListUpdate, OnRoomUpdate);
    }
    private void OnDisable()
    {
        RoomMgr.Instantce.EndCheckRoom();
        EventCentre.Instantce.RemoveEvent(EventDefine.OnRoomListUpdate, OnRoomUpdate);
        roomItem_list.ForEach(x => x.gameObject.SetActive(false));
    }
    private void OnRoomUpdate(EventObject msg)
    {
        foreach (var roomItem in roomItem_list)
            roomItem.gameObject.SetActive(false);

        var allRoomList =  (List<RoomData>)msg.msgBody;
        for(int i=0;i< allRoomList.Count; i++)
        {
            UI_RoomItem item;
            if (i < roomItem_list.Count)
            {
                item = roomItem_list[i];
                item.gameObject.SetActive(true);
               
            }
            else
            {
                item =SpwanRoomItem();
            }
            var room_data = allRoomList[i];
            item.SetUIData(room_data, () =>
            {
                Log.InfoFormat("Click Join Room {0}", Log.Color_Orange, room_data.ToString());
                RoomMgr.Instantce.RequestJoinRoom(room_data);
            });
        }
    }

    private UI_RoomItem SpwanRoomItem()
    {
        var tem_go = Instantiate(roomItemPrefab, ItemContain);
        tem_go.SetActive(true);
        var room_item = tem_go.GetComponent<UI_RoomItem>();
        roomItem_list.Add(room_item);
        return room_item;
    
    }

    private void OnDestroy()
    {
        
    }
}
